package com.smile.service.impl;

import ch.qos.logback.classic.Logger;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smile.api.AirportApi;
import com.smile.api.InspectionTaskApi;
import com.smile.api.OnSiteInspectionApi;
import com.smile.api.OperateLogApi;
import com.smile.commons.action.ActionUtils;
import com.smile.commons.page.MyBatisPlusPageConverter;
import com.smile.commons.tree.TreeBuilder;
import com.smile.commons.tree.TreeNode;
import com.smile.commons.tree.TreeUtil;
import com.smile.mapper.*;
import com.smile.model.domain.*;
import com.smile.model.dto.request.AddOrganizationRequestDTO;
import com.smile.model.dto.request.EditOrganizationRequestDTO;
import com.smile.model.dto.request.GetOrganizationListRequestDTO;
import com.smile.model.dto.request.GetOrganizationsByUserIdRequestDTO;
import com.smile.model.response.GetDroneBatteryMaintenanceInfoResponse;
import com.smile.model.response.response.*;
import com.smile.request.AddOperateLogRequest;
import com.smile.service.OrganizationService;
import feign.Retryer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toMap;

@Slf4j
@Service
public class OrganizationServiceImpl implements OrganizationService {

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private OperateLogApi operateLogApi;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AirportApi airportApi;

    @Autowired
    private DroneMapper droneMapper;

    @Autowired
    private AirportDroneMapper airportDroneMapper;

    @Autowired
    private OnSiteInspectionApi onSiteInspectionApi;
    @Autowired
    private AirportMapper airportMapper;
    @Autowired
    private Retryer retryer;

    @Autowired
    private InspectionTaskApi inspectionTaskApi;

    /**
     * 检查是否为超级管理员组织（ID为1）
     * @param organizationId 组织ID
     * @param operation 操作类型（用于错误提示）
     */
    private void checkSuperOrganizationProtection(Long organizationId, String operation) {
        if (organizationId == 1) {
            throw new RuntimeException("超级管理员组织无法" + operation);
        }
    }

    public static void main(String[] args) {
        System.out.println(StrUtil.isBlank("1"));
        System.out.println(IdWorker.getIdStr());
    }

    @Override
    public Boolean addOrganization(AddOrganizationRequestDTO addOrganizationRequestDTO) {

        QueryWrapper<SmilePlusOrganization> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("organization_name", addOrganizationRequestDTO.getOrganizationName());
        queryWrapper1.eq("delete_status", 0);
        List<SmilePlusOrganization> smilePlusOrganizations1 = organizationMapper.selectList(queryWrapper1);
        if (CollectionUtil.isNotEmpty(smilePlusOrganizations1)) {
            throw new RuntimeException("该组织已存在");
        }


        Long parentId = addOrganizationRequestDTO.getParentId();
        QueryWrapper<SmilePlusOrganization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", parentId);
        queryWrapper.eq("delete_status", 0);
        List<SmilePlusOrganization> smilePlusOrganizations = organizationMapper.selectList(queryWrapper);

        Long startTime = System.nanoTime();
        SmilePlusOrganization smilePlusOrganization = new SmilePlusOrganization();
        BeanUtil.copyProperties(addOrganizationRequestDTO, smilePlusOrganization);
        smilePlusOrganization.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
        smilePlusOrganization.setCreateTime(LocalDateTime.now());
        smilePlusOrganization.setOrganizationCode(IdWorker.getIdStr());
        smilePlusOrganization.setModifyTime(LocalDateTime.now());
        smilePlusOrganization.setDeleteStatus(Boolean.FALSE);

        if (ObjectUtil.isNull(addOrganizationRequestDTO.getParentId())) {
            smilePlusOrganization.setLevel(1);
        } else {
            // 检查上级组织是否存在
            if (CollectionUtil.isEmpty(smilePlusOrganizations)) {
                throw new RuntimeException("上级组织不存在");
            }

            if (ObjectUtil.isNull(smilePlusOrganizations.get(0).getParentId())) {
                smilePlusOrganization.setLevel(2);
            } else if (smilePlusOrganizations.get(0).getLevel() == 1) {
                smilePlusOrganization.setLevel(2);
            } else if (smilePlusOrganizations.get(0).getLevel() == 2) {
                smilePlusOrganization.setLevel(3);
            } else if (smilePlusOrganizations.get(0).getLevel() == 3) {
                throw new RuntimeException("组织最多为三级");
            }
        }

        // 计算并设置祖籍列表
        String ancestors = calculateAncestors(addOrganizationRequestDTO.getParentId());
        smilePlusOrganization.setAncestors(ancestors);

        organizationMapper.insert(smilePlusOrganization);
        Long endTime = System.nanoTime();

        AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
        addOperateLogRequest.setOperateModule("组织模块");
        addOperateLogRequest.setOperateName("添加组织");
        addOperateLogRequest.setOperateResult(Boolean.TRUE);
        addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
        addOperateLogRequest.setOperateType(1);
        addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
        addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
        addOperateLogRequest.setTimes(endTime - startTime);
        operateLogApi.addOperateLogRequest(addOperateLogRequest);

        return Boolean.TRUE;
    }

    @Override
    public Page<GetOrganizationListResponseDTO> getOrganizationList(GetOrganizationListRequestDTO getOrganizationListRequestDTO) {
        Page<SmilePlusOrganization> page = new Page<>(getOrganizationListRequestDTO.getCurrentPage(), getOrganizationListRequestDTO.getPageSize());
        QueryWrapper<SmilePlusOrganization> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(getOrganizationListRequestDTO)) {
            if (StrUtil.isNotBlank(getOrganizationListRequestDTO.getOrganizationName())) {
                queryWrapper.eq("organization_name", getOrganizationListRequestDTO.getOrganizationName());
            }
        }


        List<SmilePlusOrganization> page1 = organizationMapper.selectList(queryWrapper);
        Page<SmilePlusOrganization> page2 = new Page<>();
        page2.setRecords(page1);

        Page<GetOrganizationListResponseDTO> getOrganizationListResponseDTOPage = MyBatisPlusPageConverter.convertPage(page2, GetOrganizationListResponseDTO.class);


        return getOrganizationListResponseDTOPage.setRecords(buildOrganizationTree(getOrganizationListResponseDTOPage.getRecords()));
    }

    @Override
    public List<GetOrganizationListResponseDTO> getOrganizationList1(GetOrganizationListRequestDTO getOrganizationListRequestDTO) {
        Page<SmilePlusOrganization> page = new Page<>(getOrganizationListRequestDTO.getCurrentPage(), getOrganizationListRequestDTO.getPageSize());
        QueryWrapper<SmilePlusOrganization> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(getOrganizationListRequestDTO)) {
            if (StrUtil.isNotBlank(getOrganizationListRequestDTO.getOrganizationName())) {
                queryWrapper.eq("organization_name", getOrganizationListRequestDTO.getOrganizationName());
                queryWrapper.orderByAsc("sort");
            }
        }
        List<SmilePlusOrganization> list = organizationMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            List<SmilePlusOrganization> collect = list.stream().sorted((i1, i2) -> {
                return i1.getSort() < i2.getSort() ? i1.getSort() : i2.getSort();
            }).collect(Collectors.toList());


            // 树形方法一：
            //return buildOrganizationTree(BeanUtil.copyToList(collect, GetOrganizationListResponseDTO.class));

            // 树形方法二：
            List<GetOrganizationListResponseDTO> getOrganizationListResponseDTOS = BeanUtil.copyToList(collect, GetOrganizationListResponseDTO.class);
            // 获取父节点
            List<GetOrganizationListResponseDTO> trees = getOrganizationListResponseDTOS.stream().filter(item -> item.getParentId() == -1)
                    .map(item -> {
                        // 递归获取子节点
                        item.setChildren(getChildrens(item, getOrganizationListResponseDTOS));
                        return item;
                    }).sorted((s1, s2) -> {
                        return (s1.getSort() == null ? 0 : s1.getSort()) - (s2.getSort() == null ? 0 : s2.getSort());
                    }).collect(Collectors.toList());
            return trees;

        } else {
            return Collections.emptyList();
        }
    }

    private List<GetOrganizationListResponseDTO> getChildrens(GetOrganizationListResponseDTO parentItem, List<GetOrganizationListResponseDTO> treeDTOS) {
        return treeDTOS.stream().filter(item -> {
            return item.getParentId().equals(parentItem.getId());
        }).map(item -> {
            item.setChildren(getChildrens(item, treeDTOS));
            return item;
        }).sorted((s1, s2) -> {
            return (s1.getSort() == null ? 0 : s1.getSort()) - (s2.getSort() == null ? 0 : s2.getSort());
        }).collect(Collectors.toList());
    }

    /**
     * 获取无人机设备列表
     * @param params 参数
     * @return 返回无人机设备列表信息
     */
    @Override
    public List<GetOrganizationListResponseDTO> getDeviceList(GetOrganizationListRequestDTO params) {
        log.info("开始执行getDeviceList方法，请求参数: {}", params);

        // 1. 查询组织列表
        QueryWrapper<SmilePlusOrganization> organizationQueryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(params)) {
            if (StrUtil.isNotBlank(params.getOrganizationName())) {
                organizationQueryWrapper.eq("organization_name", params.getOrganizationName());
                organizationQueryWrapper.orderByAsc("sort");
            }
            if (ObjectUtil.isNotNull(params.getIds()) && !params.getIds().equals("")) {
                log.info("ids: {}", params.getIds());
                String[] ids = params.getIds().split(",");
                organizationQueryWrapper.in("id", (Object[]) ids);
            }
        }

        // 查询相关的组织信息列表
        List<SmilePlusOrganization> organizationList = organizationMapper.selectList(organizationQueryWrapper);
        if (CollectionUtil.isNotEmpty(organizationList)) {

            // 对组织列表进行二次排序
            List<SmilePlusOrganization> collect = organizationList.stream().sorted((i1, i2) -> {
                return i1.getSort() < i2.getSort() ? i1.getSort() : i2.getSort();
            }).toList();
            // 转换组织列表为响应对象
            List<GetOrganizationListResponseDTO> listResponseDTOS = BeanUtil.copyToList(collect, GetOrganizationListResponseDTO.class);
            List<GetOrganizationListResponseDTO> getOrganizationListResponseDTOS = new ArrayList<>();
            for (GetOrganizationListResponseDTO i : listResponseDTOS) {
                // 通过组织ID查询对应的机场
                List<FeisuanAirport> feisuanAirportList = airportMapper.selectList(new LambdaQueryWrapper<FeisuanAirport>() {{
                    eq(FeisuanAirport::getOrganizationId, i.getId());
                }});
                if (CollectionUtil.isEmpty(feisuanAirportList)) continue;

                List<GetDeviceGroup> deviceGroups = new ArrayList<>();
                // 通过机场和无人机关系查询无人机信息
                for (FeisuanAirport feisuanAirport : feisuanAirportList) {
                    // 通过关系表中的机场ID查询无人机ID
                    FeisuanAirportDrone feisuanAirportDrone = airportDroneMapper.selectOne(new LambdaQueryWrapper<FeisuanAirportDrone>() {{
                        eq(FeisuanAirportDrone::getAirportId, feisuanAirport.getId());
                        last("limit 1");
                    }});

                    List<GetDeviceItem> deviceItems = new ArrayList<>();
                    if (ObjectUtil.isNotNull(feisuanAirportDrone)) {

                        // 判断无人机是否在线 0 离线 1 在线
                        Duration  duration = Duration.between(feisuanAirport.getModifyTime(),LocalDateTime.now());
                        GetDeviceItem  deviceItem = new GetDeviceItem();
                        if (duration.toSeconds() < 20){
                            deviceItem.setStatus(1);
                        } else {
                            deviceItem.setStatus(0);
                        }
                        // 设备类型: 1 机场 2 设备
                        // 1、设置机场设备信息
                        deviceItem.setType(1);
                        deviceItem.setId(feisuanAirport.getId());
                        deviceItem.setName(feisuanAirport.getAirportName());
                        deviceItem.setModel(feisuanAirport.getDeviceModelKey());
                        deviceItem.setVideoUrl(feisuanAirport.getVideoAddress());

                        deviceItems.add(deviceItem);

                        // 场通过无人机ID查询无人机信息
                        FeisuanDrone feisuanDrone = droneMapper.selectById(feisuanAirportDrone.getDroneId());
                        if (ObjectUtil.isNotNull(feisuanDrone)) {
                            GetDeviceItem deviceItem2 = new GetDeviceItem();
                            // 2、设置无人机设备信息
                            deviceItem2.setId(feisuanDrone.getId());
                            deviceItem2.setName(feisuanDrone.getDroneName());
                            deviceItem2.setModel(feisuanDrone.getDeviceModelKey());
                            deviceItem2.setStatus(1);
                            deviceItem2.setType(2);
                            deviceItem2.setVideoUrl(feisuanDrone.getDroneVideoAddress());
                            deviceItems.add(deviceItem2);
                            GetDeviceGroup deviceGroup = new GetDeviceGroup();
                            deviceGroup.setDeviceItems(deviceItems);
                            deviceGroups.add(deviceGroup);
                       }


                    }
                }
                i.setDeviceGroups(deviceGroups);
                getOrganizationListResponseDTOS.add(i);
            }
            return getOrganizationListResponseDTOS;
        } else {
            return Collections.emptyList();
        }

        // old
        /*organizationQueryWrapper.eq("delete_status", 0);
        organizationQueryWrapper.orderByAsc("sort");
        
        List<SmilePlusOrganization> organizationList = organizationMapper.selectList(organizationQueryWrapper);
        if (CollectionUtil.isEmpty(organizationList)) {
            return Collections.emptyList();
        }

        // 2. 查询所有机场
        QueryWrapper<FeisuanAirport> airportQueryWrapper = new QueryWrapper<>();
        airportQueryWrapper.eq("delete_status", 0);
        List<FeisuanAirport> airportList = airportMapper.selectList(airportQueryWrapper);
        
        // 3. 查询机场-无人机关系
        QueryWrapper<FeisuanAirportDrone> airportDroneQueryWrapper = new QueryWrapper<>();
        List<FeisuanAirportDrone> airportDroneList = airportDroneMapper.selectList(airportDroneQueryWrapper);
        
        // 构建机场ID到无人机ID的映射关系
        Map<Long, List<Long>> airportToDroneMap = airportDroneList.stream()
                .collect(Collectors.groupingBy(
                        FeisuanAirportDrone::getAirportId,
                        Collectors.mapping(FeisuanAirportDrone::getDroneId, Collectors.toList())
                ));

        // 4. 构建组织响应数据
        List<GetOrganizationListResponseDTO> resultList = new ArrayList<>();
        
        for (SmilePlusOrganization organization : organizationList) {
            GetOrganizationListResponseDTO organizationDTO = BeanUtil.copyProperties(organization, GetOrganizationListResponseDTO.class);
            
            // 查询该组织下的所有机场
            List<FeisuanAirport> organizationAirports = airportList.stream()
                    .filter(airport -> organization.getId().equals(airport.getOrganizationId()))
                    .collect(Collectors.toList());
            
            if (CollectionUtil.isNotEmpty(organizationAirports)) {
                List<GetDeviceGroup> deviceGroups = new ArrayList<>();
                
                for (FeisuanAirport airport : organizationAirports) {
                    List<GetDeviceItem> deviceItems = new ArrayList<>();
                    
                    // 添加机场设备
                    GetDeviceItem airportItem = new GetDeviceItem();
                    airportItem.setId(airport.getId());
                    airportItem.setName(airport.getAirportName());
                    airportItem.setModel(airport.getDeviceModelKey());
                    airportItem.setType(1); // 1表示机场
                    airportItem.setVideoUrl(airport.getVideoAddress());
                    
                    // 判断机场在线状态（根据modify_time判断）
                    Duration airportDuration = Duration.between(airport.getModifyTime(), LocalDateTime.now());
                    airportItem.setStatus(airportDuration.toSeconds() < 20 ? 1 : 0);
                    deviceItems.add(airportItem);
                    
                    // 通过机场-无人机关系查询该机场下的无人机
                    List<Long> droneIds = airportToDroneMap.get(airport.getId());
                    if (CollectionUtil.isNotEmpty(droneIds)) {
                        QueryWrapper<FeisuanDrone> droneQueryWrapper = new QueryWrapper<>();
                        droneQueryWrapper.in("id", droneIds);
                        droneQueryWrapper.eq("delete_status", 0);
                        List<FeisuanDrone> droneList = droneMapper.selectList(droneQueryWrapper);
                        
                        for (FeisuanDrone drone : droneList) {
                            GetDeviceItem droneItem = new GetDeviceItem();
                            droneItem.setId(drone.getId());
                            droneItem.setName(drone.getDroneName());
                            droneItem.setModel(drone.getDeviceModelKey());
                            droneItem.setType(2); // 2表示无人机
                            droneItem.setVideoUrl(drone.getDroneVideoAddress());
                            
                            // 判断无人机在线状态
                            Duration droneDuration = Duration.between(drone.getModifyTime(), LocalDateTime.now());
                            droneItem.setStatus(droneDuration.toSeconds() < 20 ? 1 : 0);
                            deviceItems.add(droneItem);
                        }
                    }
                    
                    // 创建设备组
                    GetDeviceGroup deviceGroup = new GetDeviceGroup();
                    deviceGroup.setDeviceItems(deviceItems);
                    deviceGroups.add(deviceGroup);
                }
                
                organizationDTO.setDeviceGroups(deviceGroups);
            }
            
            resultList.add(organizationDTO);
        }
        
        log.info("getDeviceList方法执行完成，返回组织数量: {}", resultList.size());
        return resultList;*/
    }



    public List<GetOrganizationListResponseDTO> buildOrganizationTree(
            List<GetOrganizationListResponseDTO> records) {

        // 1. 准备关键数据结构
        Map<Long, GetOrganizationListResponseDTO> nodeMap = new HashMap<>();
        List<GetOrganizationListResponseDTO> roots = new ArrayList<>();

        // 2. 填充节点映射表 (ID -> Node)
        for (GetOrganizationListResponseDTO node : records) {
            nodeMap.put(node.getId(), node);
            // 初始化子节点列表 (防止后续空指针)
            if (node.getChildren() == null) {
                node.setChildren(new ArrayList<>());
            }
        }

        // 3. 构建树结构
        for (GetOrganizationListResponseDTO node : records) {
            Long parentId = node.getParentId();

            // 3.1 处理根节点 (无父节点)
            if (parentId == null || parentId == 0L || !nodeMap.containsKey(parentId)) {
                roots.add(node);
                continue;
            }

            // 3.2 挂载到父节点
            GetOrganizationListResponseDTO parent = nodeMap.get(parentId);
            if (parent.getChildren() == null) {
                parent.setChildren(new ArrayList<>());
            }
            parent.getChildren().add(node);
        }

        // 4. 对整棵树进行排序
        Comparator<GetOrganizationListResponseDTO> sortComparator = Comparator
                .comparingInt(GetOrganizationListResponseDTO::getSort);

        // 对根节点排序
        roots.sort(sortComparator);

        // 递归对所有子节点排序
        sortTreeNodes(roots, sortComparator);

        return roots;
    }

    // 递归排序树节点
    private void sortTreeNodes(List<GetOrganizationListResponseDTO> nodes,
                               Comparator<GetOrganizationListResponseDTO> comparator) {
        if (CollectionUtil.isEmpty(nodes)) {
            return;
        }

        // 排序当前层级
        nodes.sort(comparator);

        // 递归排序子节点
        for (GetOrganizationListResponseDTO node : nodes) {
            if (CollectionUtil.isNotEmpty(node.getChildren())) {
                sortTreeNodes(node.getChildren(), comparator);
            }
        }
    }


    @Override
    public GetOrganizationByIdResponseDTO getOrganizationById(Long id) {
        SmilePlusOrganization smilePlusOrganization = organizationMapper.selectById(id);
        GetOrganizationByIdResponseDTO getOrganizationByIdResponseDTO = new GetOrganizationByIdResponseDTO();
        BeanUtil.copyProperties(smilePlusOrganization, getOrganizationByIdResponseDTO);
        return getOrganizationByIdResponseDTO;
    }

    @Override
    public Boolean editOrganization(EditOrganizationRequestDTO editOrganizationRequestDTO) {
        // 检查是否为超级管理员组织，防止编辑
        checkSuperOrganizationProtection(editOrganizationRequestDTO.getId(), "编辑");

        long startTime = System.nanoTime();

        // 获取当前正在编辑的组织信息
        SmilePlusOrganization currentOrg = organizationMapper.selectById(editOrganizationRequestDTO.getId());
        if (ObjectUtil.isNull(currentOrg)) {
            throw new RuntimeException("当前组织不存在");
        }
        Integer currentLevel = currentOrg.getLevel();

        // 检查组织状态变更的合法性
        validateOrganizationStatusChange(editOrganizationRequestDTO, currentOrg);


        // 如果修改了父组织，需要校验层级限制和存在性
        if (ObjectUtil.isNotNull(editOrganizationRequestDTO.getParentId())) {
            QueryWrapper<SmilePlusOrganization> parentQueryWrapper = new QueryWrapper<>();
            parentQueryWrapper.eq("id", editOrganizationRequestDTO.getParentId());
            parentQueryWrapper.eq("delete_status", 0);
            List<SmilePlusOrganization> parentOrganizations = organizationMapper.selectList(parentQueryWrapper);

            // 检查上级组织是否存在
            if (CollectionUtil.isEmpty(parentOrganizations)) {
                throw new RuntimeException("上级组织不存在");
            }

            SmilePlusOrganization parentOrg = parentOrganizations.get(0);
            if (parentOrg.getLevel() != null && parentOrg.getLevel() == 3) {
                throw new RuntimeException("组织最多为三级：当前第二层组织存在下级组织，不能选择其他同级组织作为上级");
            }

            // 根据当前组织层级限制上级组织选择范围
            if (currentLevel != null) {
                if (currentLevel == 2) {
                    // 第二层组织选择上级的逻辑
                    validateSecondLevelParentSelection(currentOrg, parentOrg);
                } else if (currentLevel == 3) {
                    // 第三层组织可以选择其他第二层或第一层作为上级
                    if (parentOrg.getLevel() != null && parentOrg.getLevel() > 2) {
                        throw new RuntimeException("第三层组织只能选择第一层或第二层组织作为上级");
                    }
                }
            }
        }

        if (StrUtil.isNotBlank(editOrganizationRequestDTO.getOrganizationName())) {
            QueryWrapper<SmilePlusOrganization> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("organization_name", editOrganizationRequestDTO.getOrganizationName());
            queryWrapper1.eq("delete_status", 0);
            queryWrapper1.notIn("id", editOrganizationRequestDTO.getId());
            List<SmilePlusOrganization> smilePlusOrganizations1 = organizationMapper.selectList(queryWrapper1);
            if (CollectionUtil.isNotEmpty(smilePlusOrganizations1)) {
                throw new RuntimeException("该组织已存在");
            }
        }

        // 计算新的层级：只有当父组织发生变化时才重新计算
        Integer newLevel = null;
        if (ObjectUtil.isNotNull(editOrganizationRequestDTO.getParentId())
                && !Objects.equals(editOrganizationRequestDTO.getParentId(), currentOrg.getParentId())) {
            QueryWrapper<SmilePlusOrganization> parentQueryWrapper = new QueryWrapper<>();
            parentQueryWrapper.eq("id", editOrganizationRequestDTO.getParentId());
            parentQueryWrapper.eq("delete_status", 0);
            List<SmilePlusOrganization> parentOrganizations = organizationMapper.selectList(parentQueryWrapper);
            if (CollectionUtil.isNotEmpty(parentOrganizations)) {
                SmilePlusOrganization parentOrg = parentOrganizations.get(0);
                if (ObjectUtil.isNull(parentOrg.getParentId()) || parentOrg.getLevel() == 1) {
                    newLevel = 2; // 父组织为一级组织，当前组织为二级组织
                } else if (parentOrg.getLevel() == 2) {
                    newLevel = 3; // 父组织为二级组织，当前组织为三级组织
                } else if (parentOrg.getLevel() == 3) {
                    throw new RuntimeException("组织最多为三级");
                }
            } else {
                throw new RuntimeException("上级组织不存在");
            }
        }

        // 只有当父组织发生变化时才重新计算祖籍列表
        String ancestors = currentOrg.getAncestors(); // 默认使用当前祖籍
        if (ObjectUtil.isNotEmpty(editOrganizationRequestDTO.getParentId()) && 
            !editOrganizationRequestDTO.getParentId().equals(currentOrg.getParentId())) {
            // 父组织发生变化，重新计算祖籍列表
            ancestors = calculateAncestors(editOrganizationRequestDTO.getParentId());
        }

        /*// 当组织状态被设置为开启时，检查上级组织状态
        // 只有当请求明确要开启组织，并且当前组织处于禁用状态时才执行检查
        Boolean requestStatus = editOrganizationRequestDTO.getStatus();
        Boolean currentStatus = currentOrg.getStatus();
        
        // 如果请求明确要开启组织，并且当前组织不是开启状态
        if (Boolean.TRUE.equals(requestStatus) && !Boolean.TRUE.equals(currentStatus)) {
            // 检查上级组织状态：如果上级组织处于禁用状态，则不允许开启当前组织
            if (ObjectUtil.isNotNull(currentOrg.getParentId())) {
                QueryWrapper<SmilePlusOrganization> parentQueryWrapper = new QueryWrapper<>();
                parentQueryWrapper.eq("id", currentOrg.getParentId());
                parentQueryWrapper.eq("delete_status", 0);
                SmilePlusOrganization parentOrg = organizationMapper.selectOne(parentQueryWrapper);
                if (ObjectUtil.isNotNull(parentOrg) && !Boolean.TRUE.equals(parentOrg.getStatus())) {
                    throw new RuntimeException("上级组织处于禁用状态，当前组织不允许被开启");
                }
            }
        }*/
        
        UpdateWrapper<SmilePlusOrganization> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("delete_status", Boolean.FALSE)
                .eq("id", editOrganizationRequestDTO.getId())
                .set("modify_time", LocalDateTime.now())
                .set(StrUtil.isNotBlank(editOrganizationRequestDTO.getOrganizationName()),
                        "organization_name",
                        editOrganizationRequestDTO.getOrganizationName())
                .set(ObjectUtil.isNotEmpty(editOrganizationRequestDTO.getSort()),
                        "sort",
                        editOrganizationRequestDTO.getSort())
                .set(ObjectUtil.isNotEmpty(editOrganizationRequestDTO.getParentId()),
                        "parent_id",
                        editOrganizationRequestDTO.getParentId())
                .set(ObjectUtil.isNotEmpty(editOrganizationRequestDTO.getStatus()),
                        "status",
                        editOrganizationRequestDTO.getStatus())
                .set(ObjectUtil.isNotNull(newLevel),
                        "level",
                        newLevel);
        
        // 特殊处理chargeName字段：
        // 1. 当chargeName为null时，不更新charge_name字段（保持原值）
        // 2. 当chargeName不为null时，更新charge_name字段（包括空字符串，用于删除负责人）
        if (editOrganizationRequestDTO.getChargeName() != null) {
            updateWrapper.set("charge_name", editOrganizationRequestDTO.getChargeName());
        }
        
        // 只有当祖籍发生变化时才更新祖籍字段
        if (!ancestors.equals(currentOrg.getAncestors())) {
            updateWrapper.set("ancestors", ancestors);
        }

        organizationMapper.update(new SmilePlusOrganization(), updateWrapper);
        long endTime = System.nanoTime();
        // 当组织状态被设置为禁用时，执行联级禁用操作
        if (ObjectUtil.isNotNull(editOrganizationRequestDTO.getStatus()) && !editOrganizationRequestDTO.getStatus()) {
            performCascadeDisable(currentOrg);
        }

        AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
        addOperateLogRequest.setOperateModule("组织模块");
        addOperateLogRequest.setOperateName("编辑组织");
        addOperateLogRequest.setOperateResult(Boolean.TRUE);
        addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
        addOperateLogRequest.setOperateType(2);
        addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
        addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
        addOperateLogRequest.setTimes(endTime - startTime);
        operateLogApi.addOperateLogRequest(addOperateLogRequest);

        return Boolean.TRUE;
    }

    /**
     * 验证组织状态变更的合法性
     * 当组织的上级处于禁用状态时，该组织不允许被开启
     *
     * @param editRequest 编辑请求
     * @param currentOrg 当前组织
     */
    private void validateOrganizationStatusChange(EditOrganizationRequestDTO editRequest, SmilePlusOrganization currentOrg) {
        // 如果状态没有变化，则不需要检查
        if (ObjectUtil.isNull(editRequest.getStatus()) ||
                Objects.equals(editRequest.getStatus(), currentOrg.getStatus())) {
            return;
        }

        // 如果是要开启组织，需要检查上级组织状态
        if (editRequest.getStatus() && !currentOrg.getStatus()) {
            String actionLabel = Boolean.TRUE.equals(editRequest.getStatus()) ? "开启" : "关闭";
            // 检查当前组织的上级组织状态
            Long parentId = editRequest.getParentId() != null ? editRequest.getParentId() : currentOrg.getParentId();

            if (parentId != null && parentId != 0L && parentId != -1L) {
                SmilePlusOrganization parentOrg = organizationMapper.selectById(parentId);
                if (ObjectUtil.isNotNull(parentOrg)) {
                    // 检查上级组织是否被禁用
                    if (Boolean.FALSE.equals(parentOrg.getStatus())) {
                        throw new RuntimeException("组织:" + parentOrg.getOrganizationName() + " 处于禁用状态，无法" + actionLabel);
                    }

                    // 递归检查所有上级组织链的状态
                    validateParentChainStatus(parentOrg, actionLabel);
                }
            }
        }
    }

    /**
     * 递归检查上级组织链的状态
     * 确保所有上级组织都处于启用状态
     *
     * @param parentOrg 上级组织
     */
    private void validateParentChainStatus(SmilePlusOrganization parentOrg, String actionLabel) {
        if (parentOrg.getParentId() == null || parentOrg.getParentId() == 0L || parentOrg.getParentId() == -1L) {
            return; // 已到达根节点
        }

        SmilePlusOrganization grandParentOrg = organizationMapper.selectById(parentOrg.getParentId());
        if (ObjectUtil.isNotNull(grandParentOrg)) {
            if (Boolean.FALSE.equals(grandParentOrg.getStatus())) {
                throw new RuntimeException("组织：" + grandParentOrg.getOrganizationName() + " 处于禁用状态，无法" + actionLabel);
            }

            // 继续递归检查更上级的组织
            validateParentChainStatus(grandParentOrg, actionLabel);
        }
    }

    /**
     * 验证第二层组织选择上级的逻辑
     * 第二层组织在选择上级组织时有两种情况：
     * 1. 有下级时不能选择其他同级组织
     * 2. 无下级时可以选择其他同级组织
     * 
     * @param currentOrg 当前组织
     * @param parentOrg 选择的上级组织
     */
    private void validateSecondLevelParentSelection(SmilePlusOrganization currentOrg, SmilePlusOrganization parentOrg) {
        // 检查选择的上级组织层级
        if (parentOrg.getLevel() != null && parentOrg.getLevel() > 2) {
            throw new RuntimeException("第二层组织不能选择第三层组织作为上级");
        }
        
        // 如果选择的是同级组织（第二层），需要检查当前组织是否有下级
        if (parentOrg.getLevel() != null && parentOrg.getLevel() == 2) {
            // 查询当前组织是否有下级组织
            QueryWrapper<SmilePlusOrganization> childQueryWrapper = new QueryWrapper<>();
            childQueryWrapper.eq("parent_id", currentOrg.getId());
            childQueryWrapper.eq("delete_status", 0);
            List<SmilePlusOrganization> childOrganizations = organizationMapper.selectList(childQueryWrapper);
            
            if (CollectionUtil.isNotEmpty(childOrganizations)) {
                throw new RuntimeException("当前第二层组织存在下级组织，不能选择其他同级组织作为上级");
            }
        }
        
        // 如果选择的是第一层组织，则允许
        if (parentOrg.getLevel() != null && parentOrg.getLevel() == 1) {
            // 允许选择第一层组织作为上级
            return;
        }
    }

    /**
     * 计算祖籍列表
     * @param parentId 父级组织ID
     * @return 祖籍列表字符串
     */
    private String calculateAncestors(Long parentId) {

        // 检查是否为顶级组织
        if (parentId == null || parentId == -1L) {
            return "0";
        }
        // 查询父级组织
        SmilePlusOrganization parentOrg = organizationMapper.selectById(parentId);
        if (parentOrg == null) {
            return "0";
        }
        // 检查是否为顶级组织
        if (parentId == 1L) {
            return "0,1";
        }
        // 如果父级组织有祖籍列表，则添加父级组织ID
        if (!StringUtils.isEmpty(parentOrg.getAncestors())) {
            return parentOrg.getAncestors() + "," + parentId;
        }
        // 如果父级组织没有祖籍列表，则递归计算
        String parentAncestors = calculateAncestors(parentOrg.getParentId());
        return parentAncestors + "," + parentId;

    }

    @Override
    public Boolean deleteOrganization(Long id) {
        // 检查是否为超级管理员组织，防止删除
        checkSuperOrganizationProtection(id, "删除");

        Long startTime = System.nanoTime();

        // 获取当前要删除的组织信息
        SmilePlusOrganization currentOrg = organizationMapper.selectById(id);
        if (ObjectUtil.isNull(currentOrg)) {
            throw new RuntimeException("当前组织不存在");
        }

        // 执行联级删除
        performCascadeDelete(currentOrg);
        
        //删除组织下的用户
        QueryWrapper<SmilePlusUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_status", Boolean.FALSE);
        queryWrapper.eq("organization_id", id);
        userMapper.delete(queryWrapper);

        // 将对应的用户踢下线
        List<SmilePlusUser> smilePlusUsers = userMapper.selectList(new LambdaQueryWrapper<SmilePlusUser>() {{
            eq(SmilePlusUser::getOrganizationId, id);
        }});
        if (!CollectionUtil.isEmpty(smilePlusUsers)) {
            for (SmilePlusUser user : smilePlusUsers) {
                try {
                    if (StpUtil.isLogin(user.getId())) {
                        StpUtil.kickout(user.getId());
                    }
                } catch (Exception e) {
                    // 记录日志或处理异常，确保不影响其他用户的处理
                    log.error("处理用户 {} 时发生异常: {}", user.getId(), e.getMessage(), e);
                }
            }
        }


        //删除组织下的设备
        airportApi.deleteAirportByOrganizationId(id);

        //删除组织下的全部巡检计划
        onSiteInspectionApi.deleteOnSiteInspectionByOrganizationId(id);
        // 修改组织下的所有巡检任务为“已取消”状态
        inspectionTaskApi.updateTaskStatus(id, 3);

        //删除当前组织
        organizationMapper.deleteById(id);
        Long endTime = System.nanoTime();

        AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
        addOperateLogRequest.setOperateModule("组织模块");
        addOperateLogRequest.setOperateName("删除组织");
        addOperateLogRequest.setOperateResult(Boolean.TRUE);
        addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
        addOperateLogRequest.setOperateType(3);
        addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
        addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
        addOperateLogRequest.setTimes(endTime - startTime);
        operateLogApi.addOperateLogRequest(addOperateLogRequest);

        return Boolean.TRUE;
    }

    /**
     * 执行联级禁用操作
     * 禁用当前组织及其所有下级组织，并禁用相关用户
     *
     * @param currentOrg 当前要禁用的组织
     */
    private void performCascadeDisable(SmilePlusOrganization currentOrg) {
        log.info("开始执行联级禁用操作，组织ID: {}, 组织名称: {}, 组织层级: {}", 
                currentOrg.getId(), currentOrg.getOrganizationName(), currentOrg.getLevel());
        
        // 收集所有需要禁用的组织ID（包括当前组织和所有下级组织）
        List<Long> allOrgIdsToDisable = new ArrayList<>();
        allOrgIdsToDisable.add(currentOrg.getId());
        
        // 根据组织层级获取所有下级组织
        if (currentOrg.getLevel() != null && currentOrg.getLevel() <= 3) {
            if (currentOrg.getLevel() == 1) {
                // 一级组织：禁用所有二级和三级组织
                List<SmilePlusOrganization> secondLevelOrgs = organizationMapper.selectList(
                    new LambdaQueryWrapper<SmilePlusOrganization>() {{
                        eq(SmilePlusOrganization::getParentId, currentOrg.getId());
                        eq(SmilePlusOrganization::getDeleteStatus, 0);
                    }});
                
                for (SmilePlusOrganization secondOrg : secondLevelOrgs) {
                    allOrgIdsToDisable.add(secondOrg.getId());
                    
                    // 获取三级组织
                    List<SmilePlusOrganization> thirdLevelOrgs = organizationMapper.selectList(
                        new LambdaQueryWrapper<SmilePlusOrganization>() {{
                            eq(SmilePlusOrganization::getParentId, secondOrg.getId());
                            eq(SmilePlusOrganization::getDeleteStatus, 0);
                        }});
                    
                    for (SmilePlusOrganization thirdOrg : thirdLevelOrgs) {
                        allOrgIdsToDisable.add(thirdOrg.getId());
                    }
                }
                
            } else if (currentOrg.getLevel() == 2) {
                // 二级组织：禁用所有三级组织
                List<SmilePlusOrganization> thirdLevelOrgs = organizationMapper.selectList(
                    new LambdaQueryWrapper<SmilePlusOrganization>() {{
                        eq(SmilePlusOrganization::getParentId, currentOrg.getId());
                        eq(SmilePlusOrganization::getDeleteStatus, 0);
                    }});
                
                for (SmilePlusOrganization thirdOrg : thirdLevelOrgs) {
                    allOrgIdsToDisable.add(thirdOrg.getId());
                }
            }
            // 三级组织没有下级组织，只需要禁用自身
        }
        
        log.info("需要禁用的组织ID列表: {}", allOrgIdsToDisable);
        
        // 1. 禁用所有相关组织
        if (allOrgIdsToDisable.size() > 1) {
            organizationMapper.update(new SmilePlusOrganization() {{
                setStatus(false);
            }}, new LambdaQueryWrapper<SmilePlusOrganization>() {{
                in(SmilePlusOrganization::getId, allOrgIdsToDisable);
            }});
        } else {
            // 只禁用当前组织
            organizationMapper.update(new SmilePlusOrganization() {{
                setStatus(false);
            }}, new LambdaQueryWrapper<SmilePlusOrganization>() {{
                eq(SmilePlusOrganization::getId, currentOrg.getId());
            }});
        }
        
        // 2. 禁用所有相关组织下的用户
        List<SmilePlusUser> usersToDisable = userMapper.selectList(
            new LambdaQueryWrapper<SmilePlusUser>() {{
                in(SmilePlusUser::getOrganizationId, allOrgIdsToDisable);
                eq(SmilePlusUser::getDeleteStatus, 0);
            }});
        
        if (!CollectionUtil.isEmpty(usersToDisable)) {
            // 禁用用户
            userMapper.update(new SmilePlusUser() {{
                setStatus(2); // 2表示禁用状态
            }}, new LambdaQueryWrapper<SmilePlusUser>() {{
                in(SmilePlusUser::getOrganizationId, allOrgIdsToDisable);
                eq(SmilePlusUser::getDeleteStatus, 0);
            }});
            
            // 强制登出所有用户
            usersToDisable.forEach(user -> {
                try {
                    StpUtil.kickout(user.getId());
                    log.info("已强制登出用户: {}", user.getId());
                } catch (Exception e) {
                    log.warn("强制登出用户失败，用户ID: {}, 错误: {}", user.getId(), e.getMessage());
                }
            });
            
            log.info("已禁用并登出 {} 个用户", usersToDisable.size());
        }
        
        log.info("联级禁用操作完成，共禁用组织数量: {}, 禁用用户数量: {}", 
                allOrgIdsToDisable.size(), usersToDisable != null ? usersToDisable.size() : 0);
    }

    /**
     * 执行联级删除操作
     * 根据组织层级进行相应的联级删除处理
     *
     * @param currentOrg 当前要删除的组织
     */
    private void performCascadeDelete(SmilePlusOrganization currentOrg) {
        // 根据组织层级进行联级删除
        if (currentOrg.getLevel() != null && currentOrg.getLevel() <= 3) {

            if (currentOrg.getLevel() == 2) {
                // 二级组织：删除自身 + 删除所有下级三级组织
                deleteChildOrganizations(currentOrg.getId());

            } else if (currentOrg.getLevel() == 3) {
                // 三级组织：只删除自身
                // 这里不需要额外处理，因为三级组织没有下级组织
            }
        }
    }
    
    /**
     * 递归删除所有层级的子组织
     * @param parentOrgId 父组织ID
     */
    private void deleteChildOrganizations(Long parentOrgId) {
        // 查询当前二级组织的所有下级三级组织
        List<SmilePlusOrganization> thirdLevelOrgs = organizationMapper.selectList(new LambdaQueryWrapper<SmilePlusOrganization>() {{
            eq(SmilePlusOrganization::getParentId, parentOrgId);
            eq(SmilePlusOrganization::getDeleteStatus, 0);
        }});

        if (!CollectionUtil.isEmpty(thirdLevelOrgs)) {
            List<Long> thirdOrgIds = thirdLevelOrgs.stream()
                    .map(SmilePlusOrganization::getId)
                    .toList();

            // 1、删除所有下级组织下的用户
            userMapper.delete(new LambdaQueryWrapper<SmilePlusUser>() {{
                in(SmilePlusUser::getOrganizationId, thirdOrgIds);
                eq(SmilePlusUser::getDeleteStatus, 0);
            }});

            // 将对应的用户强制踢下线
            List<SmilePlusUser> smilePlusUsers = userMapper.selectList(new LambdaQueryWrapper<SmilePlusUser>() {{
                eq(SmilePlusUser::getOrganizationId, thirdOrgIds);
            }});
            if (!CollectionUtil.isEmpty(smilePlusUsers)) {
                for (SmilePlusUser user : smilePlusUsers) {
                    try {
                        if (StpUtil.isLogin(user.getId())) {
                            StpUtil.kickout(user.getId());
                        }
                    } catch (Exception e) {
                        // 记录日志或处理异常，确保不影响其他用户的处理
                        log.error("处理用户 {} 时发生异常: {}", user.getId(), e.getMessage(), e);
                    }
                }
            }

            // 2、删除所有下级组织下的设备
            for (Long thirdOrgId : thirdOrgIds) {
                airportApi.deleteAirportByOrganizationId(thirdOrgId);
            }

            // 3、删除所有下级组织下的全部巡检计划
            for (Long thirdOrgId : thirdOrgIds) {
                onSiteInspectionApi.deleteOnSiteInspectionByOrganizationId(thirdOrgId);
            }
            // 3、为每个子组织单独更新其下的巡检任务为“已取消”状态
            for (Long thirdOrgId : thirdOrgIds) {
                inspectionTaskApi.updateTaskStatus(thirdOrgId, 3);
            }

            // 4、删除所有下级组织
            organizationMapper.delete(new LambdaQueryWrapper<SmilePlusOrganization>() {{
                in(SmilePlusOrganization::getId, thirdOrgIds);
            }});
        }
    }

    @Override
    public List<GetOrganizationByUserIdResponseDTO> organizationTree(GetOrganizationsByUserIdRequestDTO getOrganizationListRequestDTO) {
        log.info("getOrganizationsByUserId getOrganizationListRequestDTO=" + getOrganizationListRequestDTO);

        if (ObjectUtil.isEmpty(getOrganizationListRequestDTO.getUserId())) {
            return Collections.emptyList();
        }

        // 1. 通过用户表查询到用户的组织ID
        SmilePlusUser smilePlusUser = userMapper.selectById(getOrganizationListRequestDTO.getUserId());
        if (ObjectUtil.isEmpty(smilePlusUser) || smilePlusUser.getOrganizationId() == null) {
            return Collections.emptyList();
        }

        // 当前登录用户ID
//        Long userId = Long.valueOf(StpUtil.getLoginId().toString());
        // 根据用户ID查询组织
//        SmilePlusUser smilePlusUser = userMapper.selectById(userId);
//        if (smilePlusUser == null) throw new RuntimeException("用户不存在!");
        SmilePlusOrganization smilePlusOrganization = organizationMapper.selectById(smilePlusUser.getOrganizationId());
        if (smilePlusOrganization == null) throw new RuntimeException("组织不存在!");

        // 当前组织的祖籍字段
        String ancestors = smilePlusOrganization.getAncestors();
        String[] orgIds = ancestors.split(",");

        // 查询所有的父级组织
        List<SmilePlusOrganization> parentOrgs = organizationMapper.selectBatchIds(Arrays.asList(orgIds));
        // 查询所有的下级组织
        List<SmilePlusOrganization> childOrgs = organizationMapper.selectList(new LambdaQueryWrapper<SmilePlusOrganization>() {{
            likeRight(SmilePlusOrganization::getAncestors, ancestors + ",");
        }});
        // 所有上下级关系数组
        List<SmilePlusOrganization> allOrgs = new ArrayList<>();
        allOrgs.add(smilePlusOrganization);
        // 父级
        if (!CollectionUtil.isEmpty(parentOrgs)) allOrgs.addAll(parentOrgs);
        // 子级
        if (!CollectionUtil.isEmpty(childOrgs)) allOrgs.addAll(childOrgs);

        // 转换为treeDTO对象
        List<GetOrganizationByUserIdResponseDTO> treeDTOs = allOrgs.stream().map(org -> {
            GetOrganizationByUserIdResponseDTO treeDTO = new GetOrganizationByUserIdResponseDTO();
            treeDTO.setId(org.getId());
            treeDTO.setOrganizationName(org.getOrganizationName());
            treeDTO.setSort(org.getSort());
            treeDTO.setStatus(org.getStatus());
            treeDTO.setChargeName(org.getChargeName());
            treeDTO.setParentId(org.getParentId());
            treeDTO.setChildren(new ArrayList<>());
            if (parentOrgs.stream().filter(item -> item.getId().equals(org.getId())).count() > 0) {
                // 0 非父级 1 父级
                treeDTO.setParentFlag(1);
            }
            return treeDTO;
        }).toList();

        // 构建树结构
        return buildOrganizationTreeForTreeDTO(treeDTOs, allOrgs);

    }

    /**
     * 构建树结构
     * @param treeDTOs 树结构DTO列表
     * @param allOrgs 所有组织列表
     * @return 树结构列表
     */
    private List<GetOrganizationByUserIdResponseDTO> buildOrganizationTreeForTreeDTO(List<GetOrganizationByUserIdResponseDTO> treeDTOs, List<SmilePlusOrganization> allOrgs) {

        if (CollectionUtil.isEmpty(treeDTOs)) return Collections.emptyList();
        // 1. 准备关键数据结构
        Map<Long, GetOrganizationByUserIdResponseDTO> nodeMap = new HashMap<>();
        Map<Long, Long> parentIdMap = new HashMap<>(); // ID -> ParentId 映射
        List<GetOrganizationByUserIdResponseDTO> roots = new ArrayList<>();

        // 2. 填充节点映射表和父级ID映射
        for (GetOrganizationByUserIdResponseDTO node : treeDTOs) {
            nodeMap.put(node.getId(), node);
        }

        // 从原始数据中获取parentId信息
        for (SmilePlusOrganization org : allOrgs) {
            parentIdMap.put(org.getId(), org.getParentId());
        }

        // 3. 构建树结构
        for (GetOrganizationByUserIdResponseDTO node : treeDTOs) {
            Long parentId = parentIdMap.get(node.getId());

            // 3.1 处理根节点 (parentId为null、0L、-1L或父节点不存在)
            if (parentId == null || parentId == 0L || parentId == -1L || !nodeMap.containsKey(parentId)) {
                roots.add(node);
                continue;
            }

            // 3.2 挂载到父节点
            GetOrganizationByUserIdResponseDTO parent = nodeMap.get(parentId);
            if (parent.getChildren() == null) {
                parent.setChildren(new ArrayList<>());
            }
            parent.getChildren().add(node);
        }

		// 4. 简单按 sort 升序排序（根与各层 children），null 排最后
		sortOrganizationTreeSimple(roots);

		return roots;
	}
	/**
	 * 按 sort 字段对组织树进行最简单的升序排序（null 排最后），递归处理所有层级
	 */
	private void sortOrganizationTreeSimple(List<GetOrganizationByUserIdResponseDTO> nodes) {
		if (CollectionUtil.isEmpty(nodes)) {
			return;
		}
		nodes.sort(Comparator.comparing(GetOrganizationByUserIdResponseDTO::getSort, Comparator.nullsLast(Integer::compareTo)));
		for (GetOrganizationByUserIdResponseDTO node : nodes) {
			if (CollectionUtil.isEmpty(node.getChildren())) {
				continue;
			}
			// children 是 List<TreeNode<Long>>，仅对 DTO 子节点排序并回填
			List<GetOrganizationByUserIdResponseDTO> dtoChildren = new ArrayList<>();
			for (TreeNode<Long> child : node.getChildren()) {
				if (child instanceof GetOrganizationByUserIdResponseDTO) {
					dtoChildren.add((GetOrganizationByUserIdResponseDTO) child);
				}
			}
			sortOrganizationTreeSimple(dtoChildren);
			List<TreeNode<Long>> rebuilt = new ArrayList<>(dtoChildren);
			node.setChildren(rebuilt);
		}
	}



    @Override
    public Map<Long, GetOrganizationByIdsResponseDTO> getOrganizationByIds(List<Long> ids) {
        List<SmilePlusOrganization> smilePlusOrganizations = organizationMapper.selectBatchIds(ids);
        List<GetOrganizationByIdsResponseDTO> getOrganizationByIdsResponseDTOS = BeanUtil.copyToList(smilePlusOrganizations, GetOrganizationByIdsResponseDTO.class);
        return getOrganizationByIdsResponseDTOS.stream().collect(toMap(GetOrganizationByIdsResponseDTO::getId, Function.identity(), (u1, u2) -> u1));
    }


}
